package com.atjava.nebula.web.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.atjava.nebula.core.constant.Constant;

public class XmlViewVariableUtil {

	private final static String VAR_SYSTIME_REGEXP = takeOnWrapper("nebula_var_systime");
	private final static String VAR_URLOBJECT = "url";
	private final static String VAR_URLPARAM_REGEXP = takeOnWrapper(VAR_URLOBJECT + "\\.([^\\}]+)");
	
	public static String evalSystemVariables(String value){
		
		if(StringUtils.isBlank(value))
			return value;
		
		value = value.replaceAll(VAR_SYSTIME_REGEXP, 
				String.valueOf(new SimpleDateFormat(Constant.DEFAULT_TIME_FORMAT).format(new Date())));
		
		return value;
	}
	
	
	public static String evalRequestParamsVariables(HttpServletRequest request,String value){
		
		if(StringUtils.isBlank(value))
			return value;
		
		Pattern p = Pattern.compile(VAR_URLPARAM_REGEXP);
		Matcher mtch = p.matcher(value);
		
		while(mtch.find()){
			String param = mtch.group(1);
			String paramValue = request.getParameter(param);
			value = value.replaceAll(takeOnWrapper(VAR_URLOBJECT + "\\."+param), paramValue);
		}
		return value;
	}
	
	public static String takeOnWrapper(String value){
		return "\\@\\{" + value + "\\}\\@";
	}
	
}
